﻿namespace Data.Repository
{
	using System.Linq;
	using System.Collections.Generic;

	public class LanguageRepository : Data.Repository.ILanguageRepository
	{
		private LinqToECommerceDBDataContext _dbContext;

		#region ILanguageRepository Members

		public int CreateNewLanguage(Data.Entity.Language theNewLanguage)
		{
			if(theNewLanguage == null)
			{
				return 0;
			}

			int result = 0;

			using(_dbContext = new LinqToECommerceDBDataContext())
			{
				result = _dbContext.ECommerce_Language_Create(theNewLanguage.Name, theNewLanguage.LanguageCulture, theNewLanguage.FlagImageFileName, theNewLanguage.Published, theNewLanguage.DisplayOrder);
			}

			return result;
		}

		public IList<Data.Entity.Language> GetAllLanguage()
		{
			List<ECommerce_GetAllLanguagesResult> lstData;

			using(_dbContext = new LinqToECommerceDBDataContext())
			{
				var data = _dbContext.ECommerce_GetAllLanguages();

				lstData = data.ToList();
			}

			if(lstData != null && lstData.Count > 0)
			{
				var result = new List<Data.Entity.Language>();

				foreach(var l in lstData)
				{
					var theEntity = new Data.Entity.Language()
					{
						DisplayOrder = l.DisplayOrder,
						FlagImageFileName = l.FlagImageFileName,
						LanguageCulture = l.LanguageCulture,
						LanguageId = l.LanguageId,
						Name = l.Name,
						Published = l.Published
					};

					result.Add(theEntity);
				}

				return result;
			}
			else
			{
				return null;
			}
		}

        public int UpdateLanguage(Data.Entity.Language theLanguage)
        {
            if (theLanguage == null || theLanguage.LanguageId <= 0)
            {
                return 0;
            }

			int result = 0;

			using(_dbContext = new LinqToECommerceDBDataContext())
			{
				var dbLanguage = (from l in _dbContext.Languages
								  where l.LanguageId == theLanguage.LanguageId
								  select l).FirstOrDefault();

				if(dbLanguage == null)
				{
					result = 0;
				}
				else
				{
					dbLanguage.DisplayOrder = theLanguage.DisplayOrder;
					dbLanguage.FlagImageFileName = theLanguage.FlagImageFileName;
					dbLanguage.LanguageCulture = theLanguage.LanguageCulture;
					dbLanguage.Name = theLanguage.Name;
					dbLanguage.Published = theLanguage.Published;

					_dbContext.SubmitChanges();

					result = 1;
				}
			}

            return result;
        }

		public int DeleteLanguage(int id)
		{
			if(id <= 0)
			{
				return 0;
			}

			int result = 0;

			using(_dbContext = new LinqToECommerceDBDataContext())
			{
				result = _dbContext.ECommerce_Language_Delete(id);
			}

			return result;
		}

		#endregion
	}
}